//
//  ZCShipmentViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/9/10.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCShipmentViewController.h"
#import "ZCTaskTitleView.h"
#import "ZCTaskTotalNumTableViewCell.h"
#import "ZCShipmentListTableViewCell.h"
#import "ZCShipmentListModel.h"
#import "ZCShipmentDetailViewController.h"

static NSString *taskNumCellID = @"ZCTaskTotalNumTableViewCell";
static NSString *shipmentListCellID = @"ZCShipmentListTableViewCell";

@interface ZCShipmentViewController ()<ZCTaskTitleViewDelegate, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

@property (nonatomic, strong) ZCTaskTitleView *taskTitleView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, strong) ZCShipmentListModel *shipListModel;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, copy) NSString *status;
@property (nonatomic, assign) BOOL failure;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UISearchBar *searchBar;

@end

@implementation ZCShipmentViewController
#pragma mark - 懒加载
- (ZCTaskTitleView *)taskTitleView {
    if (!_taskTitleView) {
        _taskTitleView = [[ZCTaskTitleView alloc] initWithFrame:CGRectMake(0, 64 + space(112), SCREENWIDTH, space(80))];
        _taskTitleView.delegate = self;
    }
    return _taskTitleView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, space(80) + 64 + space(112), SCREENWIDTH, SCREENHEIGHT - space(80) - 64 - space(112)) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        [_tableView registerClass:[ZCTaskTotalNumTableViewCell class] forCellReuseIdentifier:taskNumCellID];
        [_tableView registerClass:[ZCShipmentListTableViewCell class] forCellReuseIdentifier:shipmentListCellID];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    return _tableView;
}

- (NSMutableArray *)listArray {
    if (!_listArray) {
        _listArray = [NSMutableArray array];
    }
    return _listArray;
}

- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, space(112))];
        _searchView.backgroundColor = [UIColor whiteColor];
    }
    return _searchView;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 56)];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"请输入指令号/板车号";
    }
    return _searchBar;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBarController.tabBar.hidden = YES;
//    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"确认发运";
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [backButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.view addSubview:self.searchView];
    [self.searchView addSubview:self.searchBar];
    [self.view addSubview:self.taskTitleView];
    self.taskTitleView.titleArray = @[@"待发运",@"已发运"];
    [self.view addSubview:self.tableView];
    self.status = @"BS_CREATED";
    self.failure = NO;
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
     [self loadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = nil;
}

#pragma mark - 网络请求
- (void)loadData {
    self.currentPage = 1;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.status forKey:@"condition[status]"];
    [param setObject:@(self.currentPage) forKey:@"current"];
    [param setObject:@(10) forKey:@"size"];
    [param setObject:self.searchBar.text.length > 0 ? self.searchBar.text : @"" forKey:@"condition[key]"];
 
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = nil;
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:ShipmentList params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                weakSelf.failure = NO;
                [weakSelf.hud hideAnimated:YES];
                weakSelf.shipListModel = [ZCShipmentListModel yy_modelWithDictionary:responseObject[@"data"]];
                [weakSelf.listArray removeAllObjects];
                [weakSelf.listArray addObjectsFromArray:weakSelf.shipListModel.records];
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_header endRefreshing];
                if (weakSelf.shipListModel.records.count < 10) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }else {
                    [weakSelf.tableView.mj_footer resetNoMoreData];
                }
            }else {
                [weakSelf.tableView.mj_header endRefreshing];
                weakSelf.failure = YES;
                [weakSelf.tableView reloadData];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            [weakSelf.tableView.mj_header endRefreshing];
            weakSelf.failure = YES;
            [weakSelf.tableView reloadData];
        }];
    });
}

- (void)loadMoreData {
    self.currentPage++;
    if (self.currentPage <= [self.shipListModel.pages integerValue]) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:self.status forKey:@"condition[status]"];
        [param setObject:@(self.currentPage) forKey:@"current"];
        [param setObject:@(10) forKey:@"size"];
        
        self.hud.mode = MBProgressHUDModeIndeterminate;
        self.hud.label.text = nil;
        [self.hud showAnimated:YES];
        __weak typeof(self)weakSelf = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [ZCHttpTool postWithURL:ShipmentList params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"code"] integerValue] == 0) {
                    [weakSelf.hud hideAnimated:YES];
                    weakSelf.shipListModel = [ZCShipmentListModel yy_modelWithDictionary:responseObject[@"data"]];
                    [weakSelf.listArray addObjectsFromArray:weakSelf.shipListModel.records];
                    [weakSelf.tableView reloadData];
                    if (weakSelf.shipListModel.records.count < 10) {
                        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                    }else {
                        [weakSelf.tableView.mj_footer resetNoMoreData];
                    }
                }else {
                    [weakSelf.tableView.mj_footer endRefreshing];
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                    weakSelf.currentPage--;
                }
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                [weakSelf.tableView.mj_footer endRefreshing];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                weakSelf.currentPage--;
            }];
        });
    }else {
        self.currentPage--;
        [self.tableView.mj_footer endRefreshing];
    }
}

#pragma mark - 按钮点击
- (void)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - ZCTaskTitleViewDelegate
- (void)taskTitleViewButttonWithTitle:(NSString *)title {
    if ([title isEqualToString:@"待发运"]) {
        if (![self.status isEqualToString:@"BS_CREATED"]) {
            self.status = @"BS_CREATED";
            [self loadData];
        }
    }else if ([title isEqualToString:@"已发运"]) {
        if (![self.status isEqualToString:@"BS_DISPATCH"]) {
            self.status = @"BS_DISPATCH";
            [self loadData];
        }
    }
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    [self loadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (self.listArray.count != 0) {
        [self.listArray removeAllObjects];
        [self.tableView reloadData];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.failure) {
        return 0;
    }
    return self.listArray.count + 1;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ZCTaskTotalNumTableViewCell *taskNumCell = [tableView dequeueReusableCellWithIdentifier:taskNumCellID forIndexPath:indexPath];
        taskNumCell.selectionStyle = UITableViewCellSelectionStyleNone;
        taskNumCell.title = @"合计";
        taskNumCell.content = self.shipListModel.total;
        return taskNumCell;
    }else {
        ZCShipmentListTableViewCell *shipListCell = [tableView dequeueReusableCellWithIdentifier:shipmentListCellID forIndexPath:indexPath];
        shipListCell.selectionStyle = UITableViewCellSelectionStyleNone;
        ZCShipmentModel *shipModel = self.listArray[indexPath.section - 1];
        shipListCell.shipModel = shipModel;
        
        return shipListCell;
    }
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return space(90);
    }
    return space(300);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(20);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section > 0) {
        ZCShipmentDetailViewController *detailVC = [[ZCShipmentDetailViewController alloc] init];
        ZCShipmentModel *shipM = self.listArray[indexPath.section - 1];
        detailVC.Id = shipM.Id;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}


@end
